import xmltodict  
import json
import requests

def xml2dict(xml):
    try:
        tmp = xmltodict.parse(xml, encoding="utf-8")
        return tmp
    except Exception:
        return {}

def getstat(url="http://127.0.0.1:81/stat"):
    servers = dict()
    response = requests.get(url)
    d = response.text
    out = xml2dict(d)
    apps = out['rtmp']['server']['application']
    print("application", apps['name'])
    streams = apps['live'].get('stream')
    if streams is None:
        return

    #only one stream
    if type(streams) != list:
        streams = [streams]

    for stream in streams:
        publish = 'publishing' in stream['client'].keys()
        if publish:
            name = stream['name']
            bw = stream['bw_in']
            ip = stream['client']['address']
            if ip in servers.keys():
                servers[ip]['bw_in'] += int(bw)
                servers[ip]['rooms'] += 1
            else:
                servers[ip] = {'bw_in' : int(bw), 'rooms': 1}
    print(servers)
    response.close()

if __name__ == "__main__":
    getstat()
